﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Jayden.Dll.Web.Events
{
	public abstract class HttpEventHandler
	{
		private Dictionary<string, object> m_Events = new Dictionary<string, object>();

		public virtual string Id { get { return GetType().FullName; } }

		protected void RegisterEvent(string eventName) { m_Events.Add(eventName, null); }
		protected void AddEvent<T>(string eventName, T value)
		{
			lock (this)
			{
				try
				{
					m_Events[eventName] = (dynamic)GetEvent<T>(eventName) + value;
				}
				catch (Exception e)
				{
					throw new Exception(string.Format("Error while adding event '{0}'.", eventName), e);
				}
			}
		}
		protected void RemoveEvent<T>(string eventName, T value)
		{
			lock (this)
			{
				m_Events[eventName] = (dynamic)GetEvent<T>(eventName) - value;
			}
		}
		protected T GetEvent<T>(string eventName) { return (T)m_Events[eventName]; }

		public IEnumerable<string> Events { get { return m_Events.Keys; } }

		public void Invoke(string eventName, params object[] args)
		{
			try
			{
				MulticastDelegate d = GetEvent<MulticastDelegate>(eventName);
				if (d == null)
					return;
				Delegate[] delegates = d.GetInvocationList();
				if (delegates != null)
					foreach (Delegate item in delegates)
						item.Method.Invoke(item.Target, args);
			}
			catch (ThreadAbortException tae)
			{
				throw tae;
			}
			catch (Exception e)
			{
				throw new Exception(string.Format("Error while handling event '{0}'.", eventName), e);
			}
		}

		public override int GetHashCode() { return Id.GetHashCode(); }
		public override bool Equals(object obj)
		{
			if (obj is HttpEventHandler)
				return Id.Equals((obj as HttpEventHandler).Id);
			return false;
		}
		public override string ToString() { return Id; }

		protected virtual void ProcessRequest(HttpHandlerContext context) { }

		public virtual void ProcessBinRequest(HttpHandlerContext context) { ProcessRequest(context); }
		public virtual void ProcessHtmlRequest(HttpHandlerContext context) { ProcessRequest(context); }
		public virtual void ProcessJsonRequest(HttpHandlerContext context) { ProcessRequest(context); }
		public virtual void ProcessJsRequest(HttpHandlerContext context) { ProcessRequest(context); }
		public virtual void ProcessCssRequest(HttpHandlerContext context) { ProcessRequest(context); }
	}
}
